package com.noreply.springlearning.customparser;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

/**
 * @author noreply
 * @description
 * @datetime 2021/10/14 9:25
 */
public class MyBeanDefinitionParser implements BeanDefinitionParser {


    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        RootBeanDefinition def = new RootBeanDefinition();
        def.setBeanClassName("com.noreply.springlearning.customparser.User");
        String id = element.getAttribute("id");
        String name = element.getAttribute("name");
        String email = element.getAttribute("email");

        MutablePropertyValues pvs = def.getPropertyValues();
        if (StringUtils.hasText(name)) {
            pvs.addPropertyValue("name", name);
        }
        if (StringUtils.hasText(email)) {
            pvs.addPropertyValue("email", email);
        }
        parserContext.getRegistry().registerBeanDefinition(id, def);
        return def;
    }


}
